import { uploadImage } from '@/services/chat';
import { CloudUploadOutlined, LinkOutlined } from '@ant-design/icons';
import { Attachments, Sender } from '@ant-design/x';
import { Button, Space } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

interface IProps {
  onChat: (params: any) => void;
  isExpanded: boolean; // 正在生成代码
  isHeightAuto?: boolean;
}

const SenderChat: React.FC<IProps> = (props) => {
  const { onChat, isHeightAuto = false, isExpanded } = props;
  const [fullScreenDrop, setFullScreenDrop] = React.useState(false);
  const divRef = React.useRef<HTMLDivElement>(null);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [value, setValue] = React.useState<string>('');

  // 添加粘贴事件监听器
  useEffect(() => {
    const handlePaste = async (e: ClipboardEvent) => {
      if (e.clipboardData && e.clipboardData.items) {
        const items = e.clipboardData.items;

        for (let i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            // 阻止默认粘贴行为
            e.preventDefault();

            const blob = items[i].getAsFile();
            if (blob) {
              // 创建一个新的文件对象
              const file: any = new File(
                [blob],
                `pasted-image-${Date.now()}.png`,
                {
                  type: blob.type,
                },
              );

              // 构造上传文件需要的格式
              const uploadFile: UploadFile = {
                uid: `-${Date.now()}`,
                name: file.name,
                status: 'done',
                size: file.size,
                type: file.type,
                originFileObj: file as any,
              };

              // 添加到文件列表
              const newFileList = [...fileList];

              // 如果已有图片，移除旧的图片
              let newList = newFileList.filter(
                (f) => !f.type || !f.type.startsWith('image/'),
              );

              newList.push(uploadFile);

              // 可选：自动上传图片
              const formData = new FormData();
              formData.append('file', file);
              try {
                const { data, code } = await uploadImage(formData);

                if (code === 200) {
                  newList = newList.map((ele) =>
                    ele.name === file.name ? { ...ele, imageUrl: data } : ele,
                  );
                }
              } catch (error) {
                console.error('Failed to upload pasted image:', error);
              }
              setFileList(newList);
              break;
            }
          }
        }
      }
    };

    // 添加全局粘贴事件监听
    document.addEventListener('paste', handlePaste);

    // 组件卸载时移除事件监听
    return () => {
      document.removeEventListener('paste', handlePaste);
    };
  }, [fileList]);

  // 处理文件上传前的回调
  const handleBeforeUpload = (file: UploadFile) => {
    // 可以在这里进行文件验证
    return false;
  };

  // 处理文件变化的回调 (上传或删除)
  const handleUploadChange = async (info: any) => {
    let newFileList = [...info.fileList];

    if (
      info?.file.type.startsWith('image/') &&
      info.fileList.filter((item: any) => item.type.startsWith('image/'))
        .length > 0
    ) {
      const formData: any = new FormData();
      formData.append('file', info?.file);

      const { data, code } = await uploadImage(formData);
      if (code === 200) {
        newFileList = newFileList.map((file) =>
          file.uid === info.file.uid ? { ...file, imageUrl: data } : file,
        );
      }
    }

    // 检查是否有新上传的图片文件
    const newImageFile = newFileList.find(
      (file) =>
        file.type &&
        file.type.startsWith('image/') &&
        !fileList.some((f) => f.uid === file.uid),
    );

    if (newImageFile) {
      // 如果有新的图片文件，移除旧的图片文件
      newFileList = newFileList.filter(
        (file) =>
          !file.type ||
          !file.type.startsWith('image/') ||
          file.uid === newImageFile.uid,
      );
    }
    console.log('newFileList=>>>>>', newFileList);
    setFileList(newFileList);
  };

  const handleChange = (val: any) => {
    setValue(val);
  };

  const handleSubmit = () => {
    const data: any = { value, fileList };
    onChat && onChat(data);
    setValue('');
    setFileList([]);
  };

  return (
    <div
      className={`${styles.SenderChat} ${
        isHeightAuto ? styles.heightAuto : ''
      }`}
      ref={divRef}
    >
      {fileList.length > 0 && (
        <div className={styles.fileList}>
          <span className={styles.span}>附件</span>
          <Attachments
            overflow="wrap"
            items={fileList}
            beforeUpload={handleBeforeUpload}
            onChange={handleUploadChange}
            getDropContainer={() =>
              fullScreenDrop ? document.body : divRef.current
            }
          />
        </div>
      )}

      <Sender
        value={value}
        onChange={handleChange}
        onSubmit={handleSubmit}
        disabled={isExpanded}
        placeholder="给CodeMuse发消息"
        actions={(_, info) => {
          const { SendButton } = info.components;

          return (
            <Space size="small">
              <Attachments
                items={fileList}
                beforeUpload={handleBeforeUpload}
                disabled={isExpanded}
                onChange={handleUploadChange}
                getDropContainer={() =>
                  fullScreenDrop ? document.body : divRef.current
                }
                placeholder={{
                  icon: <CloudUploadOutlined />,
                  title: 'Drag & Drop files here',
                  description:
                    'Support file type: image, video, audio, document, etc.',
                }}
              >
                <Button type="text" icon={<LinkOutlined />} />
              </Attachments>
              <SendButton type="primary" />
            </Space>
          );
        }}
      />
    </div>
  );
};

export default SenderChat;
